package com.leetcode.annotation;

import sun.management.MethodInfo;
import sun.reflect.annotation.AnnotationParser;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by huangyugen on 2019/07/30
 **/
public class AnnotationExample {

    public static void main(String[] args) {
        try {
            //获取Student的Class对象
            Class stuClass = Class.forName("com.leetcode.annotation.AnnotationExample");

            Method stuMethod = stuClass.getMethod("a");

            if(stuMethod.isAnnotationPresent(DateSource.class)){
                System.out.println("AnnotationExample类上配置了DateSource注解！");
                //获取该元素上指定类型的注解
                DateSource cherryAnnotation = stuMethod.getAnnotation(DateSource.class);
                System.out.println("注解的值："+cherryAnnotation.value());
                //对方法操作
                System.out.println("=====开启事务====");
                try {
                    stuMethod.invoke(stuClass.newInstance());
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    System.out.println("****这个方法抛出异常了******");
                    System.out.println("****准备事务会滚了******");
                } catch (InstantiationException e) {
                    e.printStackTrace();
                }catch (RuntimeException e){
                    System.out.println("****方法抛出异常了******");
                }
                System.out.println("=====关闭事务=====");

            }else{
                System.out.println("AnnotationExample类上没有配置DateSource注解！");
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    @DateSource("nihao")
    public static void a() {
        System.out.println("我是a方法");
        System.out.println("要抛异常了");
        throw new RuntimeException();
    }
}
